/**
 * 
 */
package ro.utcn.tp.taskManagement.persistence;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import ro.utcn.tp.taskManagement.model.User;
import ro.utcn.tp.taskManagement.utils.DBUtils;

/**
 * @author Coni
 *
 */
public class UsersPersistence {
	
	public void saveUser(User user) throws Exception {
		System.out.println("saveUser(" + user.getId() + ")");
		Transaction t = null;
		Session session = PersistenceFactory.getInstance().getSession();
		try {
			t = session.beginTransaction();

			if (user.getId()==0) {
				session.save(user);
			} else {
				session.update(user);
			}
			t.commit();
		} catch (HibernateException hibernateException) {
			hibernateException.printStackTrace();
			DBUtils.rollback(t);
			throw new Exception(hibernateException);
		}
	}

	public User getUser(String username, String password) throws Exception {
		
		System.out.println("getUserId(" + username + ", " + password + ")");
		Transaction t = null;
		Session session = PersistenceFactory.getInstance().getSession();
		try {
			t = session.beginTransaction();
			Criteria criteria = session.createCriteria(User.class);
			criteria = criteria.add(Restrictions.eq("username", username));
			criteria = criteria.add(Restrictions.eq("password", password));
			criteria.setMaxResults(1);
			User user = (User) criteria.uniqueResult();
			t.commit();
			return user;
		} catch (HibernateException hibernateException) {
			hibernateException.printStackTrace();
			DBUtils.rollback(t);
			throw new Exception(hibernateException);
		}
	}

	public User getUser(int userId) throws Exception {
		System.out.println("getUser(" + userId + ")");
		Transaction t = null;
		Session session = PersistenceFactory.getInstance().getSession();
		try {
			t = session.beginTransaction();
			Criteria criteria = session.createCriteria(User.class);
			criteria = criteria.add(Restrictions.idEq(userId));
			criteria.setMaxResults(1);
			User user = (User) criteria.uniqueResult();
			t.commit();
			return user;
		} catch (HibernateException hibernateException) {
			hibernateException.printStackTrace();
			DBUtils.rollback(t);
			throw new Exception(hibernateException);
		}
	}

}
